package com.news.servlet.admin;

import com.news.model.Sort;
import com.news.service.NewsService;
import com.news.service.impl.NewsServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/admin/categoryEdit")
public class CategoryEditServlet extends HttpServlet {
    private NewsService newsService = new NewsServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取分类ID
            int categoryId = Integer.parseInt(request.getParameter("id"));
            
            // 获取分类信息
            Sort category = newsService.getSortById(categoryId);
            if (category == null) {
                throw new Exception("分类不存在");
            }
            
            // 设置属性
            request.setAttribute("category", category);
            
            // 转发到编辑页面
            request.getRequestDispatcher("/admin/category_edit.jsp").forward(request, response);
        } catch (Exception e) {
            request.getSession().setAttribute("message", "获取分类信息失败：" + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/admin/categoryManage");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取表单数据
            int sortId = Integer.parseInt(request.getParameter("sort_id"));
            String name = request.getParameter("name");

            // 检查是否是默认分类
            if (sortId <= 8) {
                throw new Exception("默认分类不允许修改");
            }

            // 获取原分类信息
            Sort category = newsService.getSortById(sortId);
            if (category == null) {
                throw new Exception("分类不存在");
            }

            // 更新分类信息
            category.setName(name);

            // 保存更新
            if (newsService.updateSort(category)) {
                request.getSession().setAttribute("message", "分类更新成功！");
                response.sendRedirect(request.getContextPath() + "/admin/categoryManage");
            } else {
                request.getSession().setAttribute("message", "分类更新失败！");
                response.sendRedirect(request.getContextPath() + "/admin/categoryEdit?id=" + sortId);
            }
        } catch (Exception e) {
            request.getSession().setAttribute("message", "分类更新失败：" + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/admin/categoryManage");
        }
    }
} 